﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.XPath;
using MN.Framework.Common;
using MN.Framework.Extensions;
using System.Xml.Linq;
using System.IO;

namespace MN.Framework.Common
{
    public class Xml
    {
        public static string EntitesAsXml(BaseContext Context, List<Type> EntitiesType)
        {
            string res = "<?xml version='1.0' ?>";
            res += "<Entities>";
            foreach (var entityType in EntitiesType)
            {
                var entityItems = Context.Set(entityType).AsEnumerable().Select(x => (BaseEntity)x).ToList();
                foreach (var item in entityItems)
                {
                    res += item.ToXml();
                }
            }
            res += "</Entities>";
            return res;
        }
        public static void SaveXmlFile(string Xml, string Path)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(Xml);
            doc.Save(Path);
        }
        public static string SaveEntityXmlData(BaseContext Context, List<Type> EntityTypes)
        {
            string res = string.Empty;
            foreach (var entityType in EntityTypes)
            {
                var entityItems = Context.Set(entityType).AsEnumerable().ToList();
                // Serialize                
                XmlSerializer serializer = new XmlSerializer(entityType);
                //FileStream fs = new FileStream("BackData.xml", FileMode.Create);
                //serializer.Serialize(fs, entityItems);
                //fs.Close();
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    serializer.Serialize(memoryStream, entityItems.SingleOrDefault());
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    using (StreamReader reader = new StreamReader(memoryStream))
                    {
                        res += reader.ReadToEnd();
                    }
                }
            }
            return res;
        }
    }
}
